/*************************************************************************
 *          HONGLING CAPITAL CONFIDENTIAL AND PROPRIETARY
 *
 *          COPYRIGHT (C) HONGLING CAPITAL CORPORATION 2012
 *    ALL RIGHTS RESERVED BY HONGLING CAPITAL CORPORATION. THIS PROGRAM
 * MUST BE USED SOLELY FOR THE PURPOSE FOR WHICH IT WAS FURNISHED BY
 * HONGLING CAPITAL CORPORATION. NO PART OF THIS PROGRAM MAY BE REPRODUCED
 * OR DISCLOSED TO OTHERS, IN ANY FORM, WITHOUT THE PRIOR WRITTEN
 * PERMISSION OF HONGLING CAPITAL CORPORATION. USE OF COPYRIGHT NOTICE
 * DOES NOT EVIDENCE PUBLICATION OF THE PROGRAM.
 *          HONGLING CAPITAL CONFIDENTIAL AND PROPRIETARY
 *************************************************************************/

package com.springboot.util;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.common.entity.BookInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * JSON序列化和反序列化辅助方法集合。
 *
 * @author Yelin.G at 2013-04-17 11:50
 *
 * @see ObjectMapper
 * @see JsonFactory
 */
public class JSONUtils {

    private static Logger logger = LoggerFactory.getLogger(JSONUtils.class);

    private JSONUtils() {
        super();
    }

    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * {@link java.util.Map Map}-><a href="http://www.json.org/">JSON</a>格式的字符串。
     *
     * @param target {@link java.util.Map Map}实例。
     * @param <T> 泛型声明。
     * @return JSON格式字符串。
     * @throws IOException {@link JsonFactory#createGenerator(java.io.Writer)}可能抛出的例外。
     * @see JsonFactory#createGenerator(java.io.Writer)
     * @see ObjectMapper#writeValue(com.fasterxml.jackson.core.JsonGenerator, Object)
     */
    public static <T> String toJSON(Object target)  {
        StringWriter writer = new StringWriter();
        try {
            mapper.writeValue(new JsonFactory().createGenerator(writer), target);
        } catch (IOException e) {
            logger.warn("write to json string error:" + target, e);
            return null;
        }
        return writer.toString();
    }

    /**
     * <a href="http://www.json.org/">JSON</a>格式的字符串->{@code <T>}对象。
     *
     * @param JSON JSON格式字符串。
     * @param clazz 要转换对象的类类型。
     * @param <T> 泛型声明。
     * @return 指定类类型的对象实例。
     * @throws IOException {@link ObjectMapper#readValue(String, Class)}可能抛出的例外。
     */
    public static <T> T toObject(String JSON, Class<T> clazz) {
        try {
            return mapper.readValue(JSON, clazz);
        } catch (IOException e) {
            logger.warn("parse json string error:" + JSON, e);
            return null;
        }
    }

    /**
     * Demo,不建议使用这个原生帮助类。
     *
     * @param args
     */
    public static void main(String[] args) {
        //可参考使用当前Demo
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("message","Hello world!");
        param.put("type","reply");
        param.put("fid", "0000fe90-6cb7-11e5-9a9d-ecf4bbd35074");
        BookInfo bookInfo = new BookInfo();
        bookInfo.setTitle("【阴阳神魔】");
        bookInfo.setPrice("99.0");
        bookInfo.setSummary("这是一部神奇的小说，天地阴阳神魔尽在其中。。。。");
        param.put("user",bookInfo);
        param.put("userID",476565);
        Map<String,Object> modify = new HashMap<String, Object>();
        modify.put("userName","楚疯子");
        modify.put("age","28");
        param.put("modify",modify);
        //Java对象转换为JSON对象，并转为Json字符串
        JSONObject json = (JSONObject) JSONObject.toJSON(param);
        System.out.println(json.toJSONString());
        //Json字符串转为JSON对象
        JSONObject fromJson = JSONObject.parseObject(json.toJSONString());
        //JSON对象转换为Java对象
        BookInfo book = JSONObject.toJavaObject(fromJson.getJSONObject("user"),BookInfo.class);
        System.out.println(book);
        Map<String,Object> userMap = JSONObject.toJavaObject(fromJson.getJSONObject("modify"),Map.class);
        System.out.println(userMap);
    }
}
